# -*- coding:utf-8 -*-
# @Author: LeoN
# @Time: 2021/2/22 23:10
from django.forms import model_to_dict
from django.shortcuts import render,redirect
from django.views.decorators.csrf import csrf_exempt
from userapp import models
from werkzeug.security import check_password_hash


def check(uname):
    # 根据用户名去数据库中查询
    if (models.UserInfo.objects.filter(uname=uname)):
        user = models.UserInfo.objects.filter(uname=uname)[0]
        u_dict = model_to_dict(user)
        #print(u_dict)
        return u_dict
    else:
        return None

@csrf_exempt
def sign(request):
    # 当前端点击登录按钮时，提交数据到后端，进入该POST方法
    if request.method == "POST":
        # 获取用户名、密码和身份
        username = request.POST.get("username")
        passwd = request.POST.get("password")
        isError = request.POST.get("isError")
        error_msg = request.POST.get("error-msg")
        identity = request.POST.get("identity")
        # 获取跳转页面链接
        next_url = request.POST.get("next_url")
        if isError != 0:
            '''
            连接数据库，对用户进行验证
            假设正确的用户名密码为"aaaaaa", "123456"
            '''
            if (check(username)):
                user=check(username)
                uname=user['uname']
                upass=user['upass']
                if username == uname and check_password_hash(upass, passwd):
                # 若登录成果，则转到用户页面
                    return redirect(next_url+'?username={}'.format(username))
                # 若用户名或密码失败,则将提示语与跳转链接继续传递到前端
                else:
                    error_msg = "用户名或密码不正确，请重新尝试"
                    return render(request, "login.html", {
                        'login_error_msg': error_msg,
                        'next_url': next_url,
                    })
            else:
                error_msg = "用户名不存在，请重新尝试"
                return render(request, "login.html", {
                    'login_error_msg': error_msg,
                    'next_url': next_url,
                })

        else :
            return render(request, "login.html", {
                    'login_error_msg': error_msg,
                    'next_url': next_url,
                })
    # 若没有进入post方法，则说明是用户刚进入到登录页面。
    # 拿到跳转链接
    next_url = '/user/'

    # 直接将跳转链接也传递到后端
    return render(request, "login.html", {'next_url': next_url,})

        
